package com.ambulance.project.biz.controller.common;

import com.alibaba.fastjson.JSON;
import com.ambulance.common.exception.CustomException;
import com.ambulance.common.utils.file.FileUploadUtils;
import com.ambulance.framework.config.MySystemConfig;
import com.ambulance.framework.config.ServerConfig;
import com.ambulance.framework.web.domain.AjaxResult;
import com.ambulance.project.biz.dto.HsDto;
import com.ambulance.project.biz.dto.HsStoreVideoDto;
import com.ambulance.project.biz.entity.Dispatch;
import com.ambulance.project.biz.service.DispatchService;
import com.ambulance.project.manager.domain.BizDispatch;
import com.ambulance.project.manager.domain.BizReport;
import com.ambulance.project.manager.service.IBizDispatchService;
import com.ambulance.project.manager.service.IBizReportService;
import com.ambulance.utils.CommonUtils;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author RXL
 * @Date 2020/6/29 19:37
 * @Version 1.0
 */
@Api(tags = "多端共用-汇声相关")
@RestController
@RequestMapping(value = "/common/v1/hs", method = RequestMethod.POST)
public class HsWorkController {

    private final static Logger logger = LoggerFactory.getLogger(HsWorkController.class);
    @Value(("${hs.baseUrl}"))
    private String baseUrl = "rtmp://47.92.143.196:1935";
    @Value(("${hs.ip}"))
    private String ip = "47.92.143.196";
    @Autowired
    private IBizDispatchService iBizDispatchService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IBizReportService iBizReportService;
    @Autowired
    private DispatchService dispatchService;

    @ApiOperation(value = "汇声发起推流", notes = "汇声发起推流", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dispatchID", value = "调度id", required = true, dataType = "int")
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = AjaxResult.class, message = "响应")
    })
    @RequestMapping(value = "/startPushStream")
    public AjaxResult startPushStream(@RequestParam(value = "dispatchID") Integer dispatchID) {
        final BizDispatch bizDispatch = new BizDispatch();
        bizDispatch.setDispatchID(dispatchID.longValue());
        bizDispatch.setHsStatus(2);
        bizDispatch.setHsRtmp(baseUrl + "/dispatch" + dispatchID + "/" + "video1");
        iBizDispatchService.updateBizDispatch(bizDispatch);
        return AjaxResult.success();
    }

    @ApiOperation(value = "汇声结束推流", notes = "汇声结束推流", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dispatchID", value = "调度id", required = true, dataType = "int")
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = AjaxResult.class, message = "响应")
    })
    @RequestMapping(value = "/stopPushStream")
    public AjaxResult stopPushStream(@RequestParam(value = "dispatchID") Integer dispatchID) {
        final BizDispatch bizDispatch = new BizDispatch();
        bizDispatch.setDispatchID(dispatchID.longValue());
        bizDispatch.setHsStatus(1);
        iBizDispatchService.updateBizDispatch(bizDispatch);
        return AjaxResult.success();
    }

    @ApiOperation(value = "汇声信息", notes = "汇声信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dispatchID", value = "调度id", required = true, dataType = "int")
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = HsDto.class, message = "响应")
    })
    @RequestMapping(value = "/hsInfo")
    public AjaxResult hsInfo(@RequestParam(value = "dispatchID") Integer dispatchID) {
        final BizDispatch bizDispatch = iBizDispatchService.selectBizDispatchById(dispatchID.longValue());
        final HsDto hsDto = new HsDto();
        hsDto.setHsRtmp(bizDispatch.getHsRtmp());
        hsDto.setHsStatus(bizDispatch.getHsStatus());
        return AjaxResult.success(hsDto);
    }


    @ApiOperation(value = "汇声上传报告", notes = "汇声上传报告", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file"),
            @ApiImplicitParam(name = "dispatchID", value = "调度id", required = true, dataType = "int")
    })
    @ApiResponses({
            @ApiResponse(code = 200, response = AjaxResult.class, message = "响应")
    })
    @RequestMapping(value = "/upload")
    public AjaxResult uploadFile(MultipartFile file,
                                 @RequestParam(value = "dispatchID") Integer dispatchID) throws Exception {
        try {
            // 上传文件路径
            String filePath = MySystemConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            final BizReport bizReport = new BizReport();
            bizReport.setDispathId(dispatchID);
            final List<BizReport> bizReports = iBizReportService.selectBizReportList(bizReport);
            bizReport.setUltrasonicReport(fileName);
            bizReport.setUltrasonicTime(LocalDateTime.now());
            if (!CommonUtils.checkNull(bizReports)) {
                iBizReportService.updateBizReport(bizReport);
            } else {
                iBizReportService.insertBizReport(bizReport);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "汇声录像", notes = "汇声录像", produces = "application/json")
    @ApiResponses({
            @ApiResponse(code = 200, response = AjaxResult.class, message = "响应")
    })
    @RequestMapping(value = "/hsStoreVideoUrl")
    public AjaxResult hsStoreVideoUrl(@RequestBody HsStoreVideoDto hsStoreVideoDto) {
//        录像地址拼接规则：http://【ip】:8080/【file中截取“html/”后面的数据】，
//        如：http://47.92.143.196:8080/car40/video1.1594177799053.flv
        if (CommonUtils.checkNull(hsStoreVideoDto.getIp())) {
            throw new CustomException("ip不能为空");
        }
        if (CommonUtils.checkNull(hsStoreVideoDto.getFile())) {
            throw new CustomException("file不能为空");
        }

        String url = "http://" + ip + ":8080/" + hsStoreVideoDto.getFile().substring(hsStoreVideoDto.getFile().indexOf("html") + 5);
        hsStoreVideoDto.setFullUrl(url);

        Integer dispatchID = Integer.parseInt(hsStoreVideoDto.getApp().substring(4));
        Dispatch dispatch = dispatchService.getById(dispatchID);
        if (CommonUtils.checkNull(dispatch)) {
            throw new CustomException("参数APP异常");
        }
        final String jsonString = JSON.toJSONString(hsStoreVideoDto);
        logger.info(jsonString);
        dispatch.setHsVideoUrl(url);
        dispatchService.updateById(dispatch);
        // 生成json文件
        // final boolean hstest = CreateFileUtil.createJsonFile(jsonString, "/home/amb/uploadPath", "hstest");
        return AjaxResult.HSsuccess();
    }
}
